import path from "path";
import json from "@rollup/plugin-json";
import resolvePlugin from "@rollup/plugin-node-resolve";
import ts from "rollup-plugin-typescript2";

// 找到packages
const packagesDir = path.resolve(__dirname, "packages");

// 根据环境变量中的TARGET，找到模块中对应的package.json
const packageDir = path.resolve(packagesDir, process.env.TARGET);

// 取到每个模块下面的package.json
const resolve = (p) => path.resolve(packageDir, p);
const pkg = require(resolve("package.json"));

// 对打包类型做一个映射表，根据每个包的package.json中配置formats来格式化需要打包的内容
const outputConfig = {
  "esm-bundler": {
    file: resolve(`dist/${process.env.TARGET}.esm-bundler.js`),
    format: "es",
  },
  cjs: {
    file: resolve(`dist/${process.env.TARGET}.cjs.js`),
    format: "cjs",
  },
  global: {
    file: resolve(`dist/${process.env.TARGET}.global.js`),
    format: "iife",
  },
};

const options = pkg.buildOptions;

// 生成rollup配置
function createConfig(format, output) {
  // 声明全局名称
  output.name = options.name;
  // 生成sourcemap
  output.sourcemap = true;

  return {
    input: resolve(`src/index.ts`),
    output,
    plugins: [
        json(), 
        ts({
            tsconfig:path.resolve(__dirname, "tsconfig.json"),
        }),
        resolvePlugin(),
    ],
  };
}

export default options.formats.map((format) => createConfig(format, outputConfig[format]));
